package com.login_2.servlet;

import com.login_2.dao.UserDao;
import com.login_2.pojo.User;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

@WebServlet("/ServletLogin2")
public class ServletLogin2 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了ServletLogin2....");

        // 设置字符编码
        request.setCharacterEncoding("utf-8");

        //获取参数对象
        Map<String, String[]> map = request.getParameterMap();

        //创建user对象
        User user = new User();

        //将map中的请求参数数据封装到user对象中
        try {
            BeanUtils.populate(user, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //调用dao
        //加载核心配置文件
        InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");

        //创建构建者对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        //获取工厂对象
        SqlSessionFactory factory = builder.build(is);

        //获取session对象
        SqlSession session = factory.openSession();

        //获取代理类对象
        UserDao userDao = session.getMapper(UserDao.class);

        //调用方法
        User u = userDao.findByUser(user);

        //提交事务
        session.commit();

        //释放资源
        session.close();

        //判断u是否为null
        if (u == null) {
            //数据库中没有跳转到login.html
            request.getRequestDispatcher("/html/login_1.html").forward(request, response);
        } else {
            //数据库中有，跳转到index.html
            request.getRequestDispatcher("/html/index.html").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
